define(function(require,exports,module) {
	// require('./plug/hammer.min');
	// require('./plug/layer/layer');
	// require('./plug/lazyload_echo');
	var myPub = require('./public');


	var oSavBtn = $('#saveBtn'); 				//提交按钮
	var oGiftCardTxt = $('.js_giftCardTxt');	//礼品卡密码输入框
	var oErrorTxt = $('.js_error');				//错误信息
	var tip_name = ['请输入密码','请输入英文或者数字'];

	//产品懒加载  异步加载 调用这个
	myPub.lazLoadingImgEcho();

	var oSendDate = $('.js_sendDate')
    oSendDate.find('li').hammer().on('tap', function () {
        oSendDate.find('li').removeClass('active')
		$(this).addClass('active')
    })

	oGiftCardTxt.on('input propertychange', function () {
		var oInputVale = oGiftCardTxt.val();
		var len = oInputVale.length;
		/*
		 //设置号码  XXXX-XXXX
		 switch (len) {
		 case 4 :
		 oGiftCardTxt.val(oInputVale + '-')
		 break;
		 case 9 :
		 oGiftCardTxt.val(oInputVale + '-')
		 break;
		 case 14 :
		 oGiftCardTxt.val(oInputVale + '-')
		 break;
		 case 5 :
		 oGiftCardTxt.val(oInputVale.substring(0,4))
		 break;
		 case 10 :
		 oGiftCardTxt.val(oInputVale.substring(0,9))
		 break;
		 case 15 :
		 oGiftCardTxt.val(oInputVale.substring(0,14))
		 break;
		 default :
		 break
		 }
		 */

		//取消格式 -
		//sCardNum = oInputVale.replace(/\-/g,'')
		sCardNum = oInputVale

		//检测输入是否正确

		CheckCar(sCardNum,function() {
			//console.log('未输入')
			oErrorTxt.text(tip_name[0]);
		},function() {
			//console.log('错误')
			oErrorTxt.text(tip_name[1]);
			oGiftCardTxt.addClass('has_erro').removeClass('has_success');
			//oSavBtn.attr('disabled','disabled');

		},function() {
			//console.log('正确')
			oGiftCardTxt.addClass('has_success').removeClass('has_erro');

			//检测提交按钮
			len == 16 ? oSavBtn.removeAttr('disabled') : oSavBtn.attr('disabled','disabled');
		})

	})

	//检测卡片格式
	function CheckCar(str,nullFn, errFn, okFn) {
		var reg = new RegExp("^[a-zA-Z0-9]+$");
		if(str == '') {
			//未输入
			if(nullFn)nullFn();
		}
		else if(!reg.test(str)){
			//输入错误
			if(errFn)errFn();
		}
		else {
			//输入正确
			if(okFn)okFn();
		}
	}

	oSavBtn.hammer().on('tap',function() {

		//确定激活 礼品卡弹框
		myPub.askLayer('确定激活礼品卡？', function() {
			$.post("/member/address/passwordCheck",{'sCardNum':sCardNum},function(data){
				if(data.status == "fail"){
					myPub.TipLayer(data.msg);
				}else if(data.status == "success"){
					window.location.href = "/member/address/success";
				}else if(data.status == "errorInfo"){
					warningLayer(erroInfo,'联系客服', function() {
						window.location.href = "http://sf.365webcall.com/chat/ChatWin3.aspx?settings=mw7mXbNN0m66066mz3Am66066mz3Am66066bz3Am6mmw0&LL=0";
					}, function() {
					}) ;
				}
			},'json');
		}, function() {

		},'激活礼品卡')

	})

	var erroInfo = '你已超过当天最大的激活次数，账户已锁定，请联系客服解锁'
	//warningLayer(erroInfo,'联系客服')

	//警告询问层方法 超过当天最大次数
	function warningLayer(sCont,sTit,yesFn,noFn,callBack) {
		layer.open({
			//no 为没有标题 sTit为设置标题
			title:sTit != 'no' ? sTit : '',
			content: sCont,
			btn: ['联系客服', '取消'],
			shadeClose: false,
			scrollbar: false,
			yes: yesFn,
			no: noFn,
			cancel:noFn,
			success:function() {
				if(callBack) callBack();
			}

		});
		myPub.NoTouchMove($('.laymshade'))
	}

	//礼品卡使用说明
	var sGiftCardIntro = '<div class="argreeMentInfo argreeMentInfo_reg"><h5><p>1、大当家礼品卡设有激活有效期,请仔细查看实体卡标注的有效期，在有效期内尽快激活，激活后将永久有效；</p></h5><h5><p>2、大当家礼品卡全场通用，订单结算时可指定礼品卡支付金额，不足部分可其他支付方式补齐；</p></h5><h5><p>3、订单金额中使用大当家礼品卡支付的部分,将不开具发票；</p></h5> <h5><p>4、退款时,大当家礼品卡支付部分退回到原礼品卡内,不予兑换；</p></h5><h5><p>5、单个账号当天验证礼品卡密码错误大于10次，则该账号自动锁定。账户锁定后，不能使用礼品卡付款或激活新卡，需联系平台客服进行解锁；</p></h5></div>	'



	$('.js_jihuo').hammer().on('tap',function() {
		myPub.TipBtnLayer(sGiftCardIntro,'使用规则')
		$('.laymshade').on('touchmove',function() {return false});
	});
	/************************************** 使用礼品卡代码 ***********************************************/

	var oUseGiftBtn = $('.js_useGiftBtn');
	var oSetNum = $('.js_setNum');
	//使用金额显示
	var oUseMoneytxt = $('.js_useMoneytxt');	//最终金额显示位置
	var oUseMoneyBtn = $('.js_useMoneyBtn'); 	//使用按钮
	var oInputMoney = $('.js_inputMoney');		//输入框
	var sBtnName = '去使用';

	var oSumPrice = oUseGiftBtn.find('.js_sumGiftPrice'); 	//剩余礼品卡的金额
	var maxGiftPrice = parseFloat(oSumPrice.text());
	var depositInput = $('#depositInput');
	var iTotalPrice = $('.js_totalPrice'); 	//产品价格
	var iGiftPrice = $('.js_giftPrice'); 	//礼品卡价格
	var sSumPrice = $('.js_sumPrice');
	var sCardNum;


	//开启和关闭礼品卡使用
	oUseGiftBtn.hammer().on('tap',function() {
		if($(this).hasClass('on')) {
			$(this).removeClass('on').find('.js_arrow').removeClass('rotate90')
			oSetNum.hide();
		}
		else {
			$(this).addClass('on').find('.js_arrow').addClass('rotate90')
			oSetNum.show();
		}
	});


	//点击使用按钮执行 .toFixed(2)
	oUseMoneyBtn.hammer().on('tap', function () {
		checkMoneyInput(oInputMoney,function() {
			myPub.TipLayer('只能输入数字或者2位小数')
			//console.log('错误')
			//oInputMoney.val(parseFloat(oInputMoney.val()).toFixed(2))
		},function() {
			//console.log('正确');
			if(oInputMoney.val() < 0 ) {
				oInputMoney.val(0);
				oUseMoneytxt.text(sBtnName);
				myPub.TipLayer('输入的数字或小数必须大于0')
			}
			else {
				oUseMoneytxt.text('- ￥'+ oInputMoney.val());
				oUseGiftBtn.removeClass('on').find('.js_arrow').removeClass('rotate90')
				oSetNum.hide();

				depositInput.val(oInputMoney.val());
				iGiftPrice.text(oInputMoney.val());
				calcLastPrice();
			}
		})
	});

	//
	oInputMoney.on('input propertychange', function () {
		var _val = parseFloat(oInputMoney.val());
		var totalPrice = parseFloat(iTotalPrice.attr("_price")).toFixed(2);
		var maxInput = totalPrice;

		if($('.couponDiscountPrice').length > 0){
			// 再计算优惠券的金额
			var couponDiscount = parseFloat($('.couponDiscountPrice').text()).toFixed(2);
			maxInput = (totalPrice - couponDiscount).toFixed(2);
		}

		if(_val < 0 ) {
			oInputMoney.val(0);
			oUseMoneytxt.text(sBtnName);
			return;
		}
		if( _val > maxGiftPrice  ||  _val > maxInput) {
			//var _maxGiftPrice
			oInputMoney.val(Math.min(maxGiftPrice, maxInput));
		}
		var _reval = oInputMoney.val().replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
		if(oInputMoney.val().length > _reval.length) {
			oInputMoney.val(_reval)
		}
	})



	/*输入框验证*/
	function checkMoneyInput(obj,fn1,fn2){
		var oIphone = obj.val();
		var reg = /^[0-9]+(.[0-9]{1,2})?$/;   //验证 正2位小数
		if (!reg.test(oIphone) ){
			if(fn1)fn1();
		}
		else {
			if(fn2)fn2();
		}
	}

	/* 计算一下待支付的总金额 */
	function calcLastPrice(){
		var totalPrice = parseFloat(iTotalPrice.attr("_price"));
		var totalDiscountPrice = 0.0;
		// 首先计算会员积分价格
		var useMember = $('.js_memberBtn').hasClass('btn_active');
		if(useMember){
			var memberPrice = parseFloat($('.js_discount').text());
			totalDiscountPrice += memberPrice;
		}
		// 再计算优惠券的金额
		var couponDiscount = parseFloat($('.couponDiscountPrice').text());
		if(couponDiscount > 0){
			totalDiscountPrice += couponDiscount;
		}
		// 计算礼品卡的金额
		var giftPrice = parseFloat(iGiftPrice.text());
		if(useMember){
			// 礼品卡的金额和会员积分不同时生效
			giftPrice = 0.0;
			iGiftPrice.text(giftPrice);
			oUseMoneytxt.text('- ￥'+ giftPrice);
		}
		if(giftPrice > totalPrice - totalDiscountPrice ){
			giftPrice = totalPrice - totalDiscountPrice;
			iGiftPrice.text(giftPrice.toFixed(2));
			oUseMoneytxt.text('- ￥'+ giftPrice.toFixed(2));
		}
		totalDiscountPrice += giftPrice;
		sSumPrice.text((totalPrice - totalDiscountPrice).toFixed(2));
	}

	exports.calcLastPrice = calcLastPrice;

	/***************************    增送他人 2017-2-15        ******************************/

	var oSwitchBtn = $('.js_switchBtn'); 			//滑动按钮框
	var oSwitchHand = $('.js_switchHand');			//滑动按钮
	var oSendFriendInfo = $('.js_sendFriendInfo'); //增送他人信息输入框

	var oClearBtn = $('.js_clearBtn');		//清除按钮

	var oUserName = $('.js_userName');  	//购买者姓名
	var oUserIphone = $('.js_userIphone');	//购买者电话



	oClearBtn.hide();

	//滑动按钮开启关闭
	oSwitchBtn.hammer().on('tap swipe',function() {
		var index = oSwitchBtn.index($(this));
		if($(this).hasClass('js_memberBtn')) {
			if(!$(this).hasClass('btn_distable')){
				ShowMemberInfo(index);
			}
		} else if($(this).hasClass('js_send')) {
			ShowSendFriendInfo(index);
		}
	});

	//会员积分
	function ShowMemberInfo(i) {
		if(oSwitchBtn.eq(i).hasClass('btn_active')) {
			//取消
			oSwitchHand.eq(i).css({ 'left':-1+'px' });
			oSwitchBtn.eq(i).removeClass('btn_active');
		} else {
			//选中
			oSwitchBtn.eq(i).addClass('btn_active')
			oSwitchHand.eq(i).css({ 'left':20+'px' });
		}
		calcLastPrice();
	}

	calcLastPrice();

	//增送他人
	function ShowSendFriendInfo(i) {
		if(oSwitchBtn.eq(i).hasClass('btn_active')) {
			oSwitchHand.eq(i).css({ 'left':-1+'px' });
			oSwitchBtn.eq(i).removeClass('btn_active');
			oSendFriendInfo.hide();
			$('input[name="isSongLi"]').val(false);
		}
		else {

			oSwitchBtn.eq(i).addClass('btn_active')
			oSwitchHand.eq(i).css({ 'left':20+'px' });
			oSendFriendInfo.show();

			oUserName.val('').parents('li').removeClass('has_error').removeClass('has_success');
			oUserIphone.val('').parents('li').removeClass('has_error').removeClass('has_success');
			oClearBtn.hide();

			$('input[name="isSongLi"]').val(true);
		}
	}





	oClearBtn.hammer().on('tap',function() {
		$(this).parents('li').removeClass('has_error').removeClass('has_success').find('.js_Text').attr('judgeBloor',false);
	})


	//购买者电话检测
	oUserIphone.on('input propertychange', function() {
		oUserIphone.siblings('.js_clearBtn').show();

		myPub.checkMobile(oUserIphone,function() {
			myPub.TipLayer('购买者手机号码不能为空！');
			oUserIphone.parents('li').removeClass('has_error').removeClass('has_success');
			oUserIphone.siblings('.js_clearBtn').hide();
			oUserIphone.attr('judgeBloor',false)
		},function() {
			oUserIphone.parents('li').addClass('has_error').removeClass('has_success')
			oUserIphone.attr('judgeBloor',false)
		},function() {
			oUserIphone.parents('li').addClass('has_success').removeClass('has_error');
			oUserIphone.attr('judgeBloor',true)
		});

	})

	//购买者姓名检测
	oUserName.on('input propertychange', function() {
		oUserName.siblings('.js_clearBtn').show();

		checkUserName(oUserName,function() {
			myPub.TipLayer('购买者姓名不能为空！');
			oUserName.parents('li').removeClass('has_error').removeClass('has_success');
			oUserName.siblings('.js_clearBtn').hide();
			oUserName.attr('judgeBloor',false)
		},function() {
			oUserName.parents('li').addClass('has_error').removeClass('has_success')
			oUserName.attr('judgeBloor',false)
		},function() {
			oUserName.parents('li').addClass('has_success').removeClass('has_error');
			oUserName.attr('judgeBloor',true)
		});

	})

	/*用户名验证*/
	function checkUserName(obj,fn1,fn2,fn3){
		var _userName = obj.val();
		var reg = /^[A-Za-z\u4e00-\u9fa5][A-Za-z0-9\u4e00-\u9fa5]{1,9}$/;   //验证用户名

		if(_userName == '') {
			if(fn1)fn1()
		}
		else if (!reg.test(_userName) ){

			if(fn2)fn2();
		}
		else {
			if(fn3)fn3();
		}
	}


});